import { defineStore } from "pinia";
import http from "@/utils/http";
import { watch } from "vue";

export const usePublicDataStore = defineStore("publicData", {
   state: () => ({
      routerName: '',
      routerPath: '',
      baseURL: http.baseURL,
      breadcrumbs: [],
      openRouter: "",
      qqMapKey: "TWUBZ-KQEKJ-SGEFE-XFZF3-KM226-VPBMX",
      merchantId: "", // 加盟商id
      merchant_manager_id: "", // 法人手机号是否重复id
      // addTarget: 0, // 新增目标页

   }),
   actions: {

      //修改routerName
      setRouterName(name) {
         this.routerName = name;
      },
      //修改routerPath
      setRouterPath(path) {
         this.routerPath = path;
      },
      // 加盟商账号id状态,用于添加加盟商后面所有的ID
      setMerchantId(id) {
         this.merchantId = id;
      },
      setMerchantManagerId(id) {
         this.merchant_manager_id = id;
      },
      // 获取已添加的单个加盟商未添加的信息页
      // setAddTatget(val) {
      //    this.addTarget = val;
      // },
      // 更新当前路由
      setOpenRouter(path) {
         this.openRouter = path;
         // 更新 breadcrumbs 中的 status
         this.breadcrumbs.forEach((item) => {
            item.status = item.path === this.openRouter;
         });
      },
      // 删除面包屑
      removeBreadcrumb(path, router) {
         const index = this.breadcrumbs.findIndex((item) => item.path === path);
         if (index !== -1) {
            const wasSelected = this.breadcrumbs[index].status; // 记录是否是选中的面包屑
            this.breadcrumbs.splice(index, 1); // 使用 splice 确保状态变化

            // 如果还有剩余的面包屑，并且删除的是选中的面包屑
            if (this.breadcrumbs.length > 0 && wasSelected) {
               let newIndex = index > 0 ? index - 1 : 0; // 如果删除的是第一个元素，则选择新的第一个
               const newBreadcrumb = this.breadcrumbs[newIndex];
               this.openRouter = newBreadcrumb.path;
               // 使用 Vue Router 的 router.replace 跳转
               router.replace(newBreadcrumb.path);
            } else if (this.breadcrumbs.length === 0) {
               // 如果没有剩余的面包屑，跳转到首页
               router.replace(this.routerPath);
            }
         }
      },
      // 新增面包屑
      setBreadcrumbs(data) {
         if (data.name == undefined) return;
         const existingPathIndex = this.breadcrumbs.findIndex((item) => item.path === data.path);
         if (existingPathIndex === -1) {
            // 如果不存在，则追加新的路径，status 默认为 false
            this.breadcrumbs.push({
               name: data.name,
               path: data.path,
               status: data.path === this.openRouter, // 根据当前 openRouter 设置 status
            });
         } else {
            // 如果路径已存在，更新状态
            this.breadcrumbs[existingPathIndex].status = data.path === this.openRouter;
         }
         this.ensureHomeIsFirst();
      },
      // 确保首页始终位于第一位
      ensureHomeIsFirst() {
         const homeIndex = this.breadcrumbs.findIndex((item) => item.name === this.routerName);
         if (homeIndex > 0) {
            const home = this.breadcrumbs.splice(homeIndex, 1)[0];
            this.breadcrumbs.unshift(home);
         }
      },
      // 刷新页面
      refreshPage(path, router) {
         // 使用更安全的方式刷新页面，避免组件卸载问题
         // router.go(0) // 注释掉可能导致问题的代码

         // 替代方案：重新导航到当前路由
         const currentRoute = router.currentRoute.value;
         router.replace({
            path: currentRoute.path,
            query: currentRoute.query,
            params: currentRoute.params
         });
      },
      // 关闭其他
      closeOthers(path, router) {
         const homeIndex = this.breadcrumbs.findIndex((item) => item.name === this.routerName);
         const currentIndex = this.breadcrumbs.findIndex((item) => item.path === path);

         if (currentIndex !== -1) {
            this.breadcrumbs = this.breadcrumbs.filter((item, index) => {
               return index === homeIndex || index === currentIndex;
            });
            this.openRouter = path;
            router.replace(path);
         }
      },
      // 关闭右侧
      closeRight(path, router) {
         const currentIndex = this.breadcrumbs.findIndex((item) => item.path === path);
         if (currentIndex !== -1) {
            this.breadcrumbs = this.breadcrumbs.slice(0, currentIndex + 1);
            this.openRouter = path;
            router.replace(path);
         }
      },
      // 关闭左侧
      closeLeft(path, router) {
         const currentIndex = this.breadcrumbs.findIndex((item) => item.path === path);
         if (currentIndex !== -1 && currentIndex > 0) { // 确保当前面包屑不是首页
            // 保留首页和当前面包屑
            this.breadcrumbs = [
               this.breadcrumbs[0], // 首页
               ...this.breadcrumbs.slice(currentIndex) // 当前面包屑及其右侧的所有面包屑
            ];
            this.openRouter = path;
            router.replace(path);
         }
      },

      //清空breadcrumbs
      clearBreadcrumbs() {
         this.breadcrumbs = [];
         this.openRouter = "";
      },
      // 全部关闭
      closeAll(router) {
         // 只保留首页
         this.breadcrumbs = this.breadcrumbs.filter((item) => item.name === this.routerName);
         this.openRouter = this.routerPath; // 确保 openRouter 设置为首页路径
         router.replace(this.routerPath); // 跳转到首页
      }
   },
   persist: { // 持久化存储
      enabled: true,
      strategies: [
         {
            key: "publicData", // 存储在 localStorage 的 key
            storage: sessionStorage, // 可以选择 sessionStorage 或 localStorage
            paths: ["breadcrumbs", "openRouter"], // 仅持久化这两个字段
         },
      ],
   },
   setup(state) {
      // 监听 breadcrumbs 数组的变化
      watch(
         () => state.breadcrumbs,
         (newBreadcrumbs) => {
            console.log(newBreadcrumbs, '触发了');

            state.ensureHomeIsFirst(); // 每次 breadcrumbs 变化时，确保首页始终位于第一位
         },
         { deep: true }
      );
   },
});